'''
Author: 码上talk|RC
Date: 2020-09-24 08:49:37
LastEditTime: 2020-09-24 10:09:55
LastEditors: 码上talk|RC
Description: 
FilePath: /charis-api/utils/rabbitmq_producer_util.py
微信:  13680065830
邮箱:  3189482282@qq.com
oops: Just do what I think it is right
'''
import pika
import json


class RabbitmqProducerUtil():
    def __init__(self, config={
        'user': 'guest',
        'passwd': 'guest',
        'ip': '127.0.0.1',
        'port': '7001',
        'virtual_host': '/'
    }):
        self.config = config
        self.connection = None
        self.channel = None
        self.routing_key = ''
        self._connect()

    def _connect(self):
        credentials = pika.PlainCredentials(
            self.config['user'], self.config['passwd'])
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(
            host=self.config['ip'], port=self.config['port'], virtual_host=self.config['virtual_host'], credentials=credentials))

    def _setQueue(self, queue):
        self.routing_key = queue
        self.channel = self.connection.channel()
        result = self.channel.queue_declare(queue=queue)

    def basic_publish(self, queue, message):
        self._setQueue(queue)
        jsonMessage = json.dumps(message)
        self.channel.basic_publish(
            exchange='', routing_key=self.routing_key, body=jsonMessage)

    def close(self):
        self.connection.close()
